"""
JH子系统专用FastAPI应用
跳过lightrag相关功能，专注于JH AI聊天服务
"""

from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from typing import Dict, List, Any, Optional
from datetime import datetime
import uvicorn

from .dependencies import create_tables
from .routes.jh_chat import router as jh_chat_router
from .routes.jh_routes import router as jh_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理 - JH简化版"""
    # 启动时初始化
    try:
        print("🚀 初始化JH子系统...")
        
        # 创建数据库表
        create_tables()
        print("✅ 数据库表创建/更新成功!")
        
        print("✅ JH系统初始化成功!")
        yield
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        raise
    finally:
        # 关闭时清理
        print("🛑 关闭JH系统...")
        print("✅ 关闭完成")


# 创建FastAPI应用
app = FastAPI(
    title="BoLe JH Subsystem API",
    description="JH子系统AI聊天服务 - 专注于求职者AI助手功能",
    version="0.1.0",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册JH相关路由
app.include_router(jh_chat_router, prefix="/api")  # JH AI聊天路由
app.include_router(jh_router, prefix="/api")  # JH数据路由


# ================================
# 健康检查和系统状态接口
# ================================

@app.get("/health")
async def health_check():
    """健康检查接口"""
    try:
        return {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "services": {
                "api": True,
                "database": True,
                "jh_chat": True,
                "agents": False  # lightrag开发中
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"Health check failed: {str(e)}"
        )


@app.get("/status")
async def get_system_status():
    """获取系统状态"""
    try:
        return {
            "status": "operational",
            "timestamp": datetime.now().isoformat(),
            "components": {
                "api_server": True,
                "database": True,
                "jh_chat_service": True,
                "agent_system": False  # lightrag开发中
            },
            "version": "0.1.0-jh"
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get system status: {str(e)}"
        )


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "BoLe JH子系统AI聊天服务",
        "version": "0.1.0-jh",
        "endpoints": {
            "health": "/health",
            "status": "/status",
            "chat_status": "/api/jh/chat/status",
            "chat_message": "/api/jh/chat/message",
            "jh_dashboard": "/frontend/jh_subsystem/jh_dashboard.html"
        }
    }


if __name__ == "__main__":
    print("🎯 JH子系统AI聊天服务器")
    print("="*50)
    uvicorn.run(
        "src.services.api.main_jh:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    ) 